package cn.itcast.hotel.Listener;

import cn.itcast.hotel.constant.MqConstants;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.HotelService;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
@Slf4j
public class MqListener {

    private final HotelService hotelService;

    private final RestHighLevelClient restHighLevelClient;

    /**
     * 酒店插入和更新队列监听器
     *
     * @param hotelId 酒店标识
     */
    @RabbitListener(queues = MqConstants.HOTEL_INSERT_QUEUE)
    public void hotelInsertAndUpdateQueueListener(Long hotelId) {
        try {
            Hotel hotel = hotelService.getById(hotelId);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            IndexRequest indexRequest = new IndexRequest("hotel").id(String.valueOf(hotelId));
            indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES酒店插入或更新失败");
            throw new RuntimeException(e);
        }
    }

    /**
     * 酒店删除队列列表
     *
     * @param hotelId 酒店标识
     */
    @RabbitListener(queues = MqConstants.HOTEL_DELETE_QUEUE)
    public void hotelDeleteQueueLister(Long hotelId) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest("hotel").id(String.valueOf(hotelId));
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES酒店删除失败");
            throw new RuntimeException(e);
        }
    }
}
